<?php
namespace Cmf\Forms;

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Email as Mail;
use Phalcon\Forms\Element\Password;
use Phalcon\Forms\Element\Submit;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Email;

/**
 * 用户菜单
 */
class UserForm extends Form
{
	public function initialize($user,$action = null)
	{
		$account = new Text('account',[
			'placeholder'             => '请输入用户账号',
			'required'                => 'required',
			'data-validation-message' => '用户账号不能为空',
		]);
		$account->setLabel('用户账号');
		$account->addValidators([new PresenceOf(['message' => '用户账号不能为空'])]);
		$this->add($account);

		$email = new Mail('email',[
			'placeholder'             => '请输入用户邮箱',
			'required'                => 'required',
			'data-validation-message' => '邮箱格式不正确',
		]);
		$email->addValidators([
			new PresenceOf(['message' => '用户邮箱不能为空']),
			new Email(['message' => '邮箱格式不对']),
		]);
		$email->setLabel('用户邮箱');
		$this->add($email);

		$name = new Text('name',[
			'placeholder'             => '请输入用户名称',
			'required'                => 'required',
			'data-validation-message' => '用户名称不能为空',
		]);
		$name->addValidators([new PresenceOf(['message' => '用户名称不能为空'])]);
		$name->setLabel('用户名称');
		$this->add($name);

		$password = new Password('password',[
			'placeholder'             => '请输入用户密码',
			'required'                => 'required',
			'data-validation-message' => '用户密码不能为空',
		]);
		$password->addValidators([new PresenceOf(['message' => '用户密码不能为空'])]);
		$password->setLabel('用户密码');
		$this->add($password);

		if($user === null) {
			$rePassword = new Password('repassword',[
				'placeholder'             => '请确认用户密码',
				'data-equal-to'           => '#password',
				'required'                => 'required',
				'data-validation-message' => '密码不一致',
			]);
			$rePassword->setLabel('确认密码');
			$this->add($rePassword);
		}

		$submit = new Submit('submit',['value' => '保存修改','class' => 'am-btn am-btn-primary']);
		$this->add($submit);

		if($user !== null && $action === 'edit') {
			$id = new Hidden('id');
			$this->add($id);

			$role_id = new Hidden('role_id');
			$this->add($role_id);
		}
	}

	public function renderDecorated($name)
	{
		$element = $this->get($name);
		$messages = $this->getMessagesFor($element->getName());

		if(!in_array($element->getName(),['id','role_id'])) {
			$input = '<div class="am-form-group">';
			$input .= '<label for="'.$element->getName().'" class="am-u-sm-3 am-form-label">'
				.$element->getLabel()
				.'</label>'
				.'<div class="am-u-sm-9">'
				.$element
				.'</div>';

			if(count($messages)) {
				$input .= '<div class="am-alert-flash am-u-sm-9">';
				foreach($messages as $message) {
					$input .= $this->flash->error($message);
				}
				$input .= '</div>';
			}
			$input .= '</div>';
		} else {
			$input = $element;
		}

		echo $input;
	}
}
